package org.ngmj.client.rpc;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.ngmj.client.handler.RpcResponseMessageHandler;
import org.ngmj.client.rpc.proxy.ProxyHandler;
import org.ngmj.protocol.MessageCodecSharable;
import org.ngmj.protocol.ProtocolFrameDecoder;
import org.ngmj.server.service.HelloService;

@Slf4j
public class JDKProxyClient {

    private static Channel channel;
    private static final Object lock = new Object();

    public static Channel getChannel() {
        if (channel != null) {
            return channel;
        }
        synchronized (lock) {
            if (channel != null) {
                return channel;
            }
            init();
            return channel;
        }
    }

    public static void main(String[] args) {
        HelloService  helloService = getProxyService(HelloService.class, getChannel());
        System.out.println(helloService.hello("nihao "));
        System.out.println(helloService.hello("world "));
        System.out.println(helloService.hello("hello "));
    }

    public static void init() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        RpcResponseMessageHandler RPC_HANDLER = new RpcResponseMessageHandler();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.group(group);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new ProtocolFrameDecoder());
                ch.pipeline().addLast(LOGGING_HANDLER);
                ch.pipeline().addLast(MESSAGE_CODEC);
                ch.pipeline().addLast(RPC_HANDLER);
            }
        });
        try {
            channel = bootstrap.connect("localhost", 8080).sync().channel();
            channel.closeFuture().addListener(future -> {
                group.shutdownGracefully();
            });
        } catch (Exception e) {
            log.error("client error", e);
        }
    }

    public static <T> T getProxyService(Class<T> interfaceClass, Channel channel) {
        return (T) ProxyHandler.newProxyInstance(interfaceClass, channel);
    }
}
